package com.cloudsigns.factorymanager2.project.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bumptech.glide.Glide;
import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.engineering.IView.IUploadPhotoView;
import com.cloudsigns.factorymanager2.engineering.bean.DialogItemBean;
import com.cloudsigns.factorymanager2.engineering.customview.BottomListDialog;
import com.cloudsigns.factorymanager2.engineering.customview.DateViewDialog;
import com.cloudsigns.factorymanager2.engineering.presenter.UploadPhotoPresenter;
import com.cloudsigns.factorymanager2.engineering.utils.PhotoUtil;
import com.cloudsigns.factorymanager2.project.adapter.ProductInformationAdapter;
import com.cloudsigns.factorymanager2.project.bean.ProductBean;
import com.cloudsigns.factorymanager2.project.iview.IAddEngineeringInstallationOrderView;
import com.cloudsigns.factorymanager2.project.myinerface.ItemRemoveListener;
import com.cloudsigns.factorymanager2.project.presenter.AddEngineeringInstallationOrderPresenter;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.DateUtil;
import com.cloudsigns.factorymanager2.project.utils.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class AddEngineeringInstallationOrderActivity1 extends Activity implements View.OnClickListener,
        BottomListDialog.OnItemDialogClick,
        ItemRemoveListener,
        IAddEngineeringInstallationOrderView,
        IUploadPhotoView,
        OnGetGeoCoderResultListener {

    private View rl_back;
    private TextView tv_title;
    //    private ImageView img_add_product;
    private ImageView iv_schematic_diagram;
    private View img_add_product;
    private ListView lv;
    private TextView btn_save;
    private EditText edt_completion_date;
    private ImageView img_completion_date;
    private EditText edt_engineering_city;
    private EditText edt__engineering_address;
    private EditText edt__engineering_name;
    private EditText edt__project_name;
    //    private GridView gridView;
//    private GridAdapter gridAdapter;
//    private List<String> pathList = new ArrayList<>();
    private String serverUrl = "";
    private String filePath;
    private ProductInformationAdapter adapter;
    private List<ProductBean> productBeanList = new ArrayList<>();
    private String TAG = AddEngineeringInstallationOrderActivity1.class.getSimpleName();
    private AddEngineeringInstallationOrderPresenter addEngineeringInstallationOrderPresenter;
    //    private AddEngineeringInstallationOrderPresenter1 addEngineeringInstallationOrderPresenter;
    private UploadPhotoPresenter uploadPhotoPresenter;
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private double lat, lon;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_add_engineering_installation_order1);

        addEngineeringInstallationOrderPresenter = new AddEngineeringInstallationOrderPresenter(this);
        uploadPhotoPresenter = new UploadPhotoPresenter(this);
        init();

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
    }

    private void init() {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        img_add_product = findViewById(R.id.img_add_product);
        lv = findViewById(R.id.lv);
        iv_schematic_diagram = findViewById(R.id.iv_schematic_diagram);
        btn_save = findViewById(R.id.btn_save);
        edt_completion_date = findViewById(R.id.edt_completion_date);
        img_completion_date = findViewById(R.id.img_completion_date);
        edt__engineering_address = findViewById(R.id.edt__engineering_address);
        edt_engineering_city = findViewById(R.id.edt_engineering_city);
        edt__engineering_name = findViewById(R.id.edt__engineering_name);
        edt__project_name = findViewById(R.id.edt__project_name);

//        pathList.add("paizhao");
//        gridView = findViewById(R.id.gridView);
//        gridView.setNumColumns(3);
//        gridAdapter = new GridAdapter(this);
//        gridAdapter.setData(pathList);
//        gridView.setAdapter(gridAdapter);
//
//        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
//
//                String imgs = (String) parent.getItemAtPosition(position);
//                if ("paizhao".equals(imgs)) {
//                    showListDialog();
//                } else {
////                    Toast.makeText(MainActivity.this, "1" + position, Toast.LENGTH_SHORT).show();
////                    PhotoPreviewIntent intent = new PhotoPreviewIntent(MainActivity.this);
////                    intent.setCurrentItem(position);
////                    intent.setPhotoPaths(imagePaths);
////                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
//                }
//            }
//        });


        tv_title.setText(getResources().getText(R.string.engineering_installation_order));
        rl_back.setOnClickListener(this);
        img_add_product.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        img_completion_date.setOnClickListener(this);
        iv_schematic_diagram.setOnClickListener(this);

        adapter = new ProductInformationAdapter(this, TAG);
        adapter.setRemoveListener(this);
        adapter.setData(productBeanList);
        lv.setAdapter(adapter);
    }

    private void save() {
        String addres_str = edt__engineering_address.getText().toString().trim();
        if (TextUtils.isEmpty(addres_str)) {
            Toast.makeText(this, "地址不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        mSearch.geocode(new GeoCodeOption()
                .city(edt_engineering_city.getText().toString().trim())
                .address(edt__engineering_address.getText().toString().trim()));

    }


    private void showListDialog() {
        DialogItemBean[] items = new DialogItemBean[]{
                new DialogItemBean(R.string.camera,
                        R.layout.dialog_list_item_normal),
                new DialogItemBean(R.string.gallary,
                        R.layout.dialog_list_item_normal),
                new DialogItemBean(R.string.cancel,
                        R.layout.dialog_list_item_normal)};
        BottomListDialog dialog = new BottomListDialog(this, Arrays.asList(items));
        dialog.setItemClick(this);
        dialog.show();
    }

    @Override
    public void onItemDialogClick(DialogItemBean item) {

        switch (item.getmTextId()) {
            case R.string.camera: {
                PhotoUtil.startCamear(AddEngineeringInstallationOrderActivity1.this, null);
                break;
            }
            case R.string.gallary: {
                PhotoUtil.startGallery(AddEngineeringInstallationOrderActivity1.this, null);
                break;
            }
            default:
                break;
        }

    }


    @Override
    public void remove(int positon) {  //列表中删除事件
        if (positon >= 0 && positon < productBeanList.size()) {
            productBeanList.remove(positon);
            adapter.setData(productBeanList);
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void remove(View view) {

    }

    private void showDateDialog() {
        DateViewDialog endDateChooseDialog = new DateViewDialog(this,
                new DateViewDialog.DateChooseInterface() {
                    @Override
                    public void getDateTime(String time, boolean longTimeChecked) {
                        edt_completion_date.setText(time);
                    }
                });
        endDateChooseDialog.setTimePickerGone(true);

        Calendar dateAndTime = Calendar.getInstance(Locale.getDefault());

        endDateChooseDialog.setDateDialogTitle(dateAndTime.get(Calendar.YEAR) + "-" + (dateAndTime.get(Calendar.MONTH) + 1) + "-" + dateAndTime.get(Calendar.DAY_OF_MONTH));
        endDateChooseDialog.showDateChooseDialog();

    }


    @Override
    public void onClick(View view) {
        TextView tv;
        Intent mIntent;
        switch (view.getId()) {
            // 返回
            case R.id.rl_back:
                finish();
                break;
            // 产品信息
            case R.id.img_add_product:
//                mIntent = new Intent(AddEngineeringInstallationOrderActivity1.this, AddProductInfomationActivity.class);
                mIntent = new Intent(AddEngineeringInstallationOrderActivity1.this, AddProductInfomationActivity1.class);
                mIntent.putExtra("type", "engineeringInstall");
                startActivityForResult(mIntent, ConstantUtil.ADD_PRODUCT_INFOMATION);
                break;
            // 完成日期
            case R.id.img_completion_date:
                showDateDialog();
                break;
            // 保存
            case R.id.btn_save:
                save();
                break;
            // 示意图
            case R.id.iv_schematic_diagram:
                showListDialog();
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ConstantUtil.ADD_PRODUCT_INFOMATION: //添加产品信息
                if (data != null) {
                    ProductBean productBean = (ProductBean) data.getSerializableExtra(ConstantUtil.PRODUCTBEAN);
                    if (productBean != null) {
                        productBeanList.add(productBean);
                        adapter.setData(productBeanList);
                        adapter.notifyDataSetChanged();
                    }


                }
                break;
            case PhotoUtil.CAMERA:
                if (resultCode == RESULT_OK) {
                    File picture = new File(PhotoUtil.filePath);
                    if (!picture.exists()) {
                        picture = new File(PhotoUtil.filePath);
                    }

                    filePath = PhotoUtil.CAMERA_SEVER + picture.getName();
                    filePath = PhotoUtil.imageCompressionAndSave(picture.getAbsolutePath(), filePath);
                    //override(100, 100)


//                    if (pathList.contains("paizhao")) {
//                        pathList.remove("paizhao");
//                    }
//                    if (pathList.size() < 3) {
//                        pathList.add(filePath);
////                        if (pathList.size() < 3)
////                            pathList.add("paizhao");
////
////                        gridAdapter.setData(pathList);
////                        gridAdapter.notifyDataSetChanged();
//                    }

                    Log.e(TAG, "----filePath=" + filePath);

                    Glide.with(AddEngineeringInstallationOrderActivity1.this).load(new File(filePath)).error(R.drawable.bg_photo_selector).into(iv_schematic_diagram);


                    uploadPhotoPresenter.uploadPhtoto();

                }

                break;
            case PhotoUtil.GALLERY:
                if (resultCode == RESULT_OK) {

                    String path = FileUtil.getRealPathFromURI(this, Uri.parse(data.getData() + ""));

//                    if (pathList.contains("paizhao")) {
//                        pathList.remove("paizhao");
//                    }
//
//                    if (pathList.size() < 3) {
//
//                        pathList.add(path);
////                        if (pathList.size() < 3)
////                            pathList.add("paizhao");
////                        gridAdapter.setData(pathList);
////                        gridAdapter.notifyDataSetChanged();
//                    }

                    Log.e(TAG, "----path=" + path);

                    Glide.with(AddEngineeringInstallationOrderActivity1.this).load(new File(path)).error(R.drawable.bg_photo_selector).into(iv_schematic_diagram);


                    File f = new File(path);
                    filePath = PhotoUtil.CAMERA_SEVER + f.getName();
                    filePath = PhotoUtil.imageCompressionAndSave(path, filePath);
//                    filePath = data.getData() + "";
                    uploadPhotoPresenter.uploadPhtoto();
//                    if (f.exists()) {
//                        f.delete();
//                    }

                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        mSearch.destroy();
        super.onDestroy();

    }

    @Override
    public long getCompleteDate() {
        long mills = DateUtil.getMillis(edt_completion_date.getText().toString().trim());
        String date = DateUtil.getYyyy_Mm_Dd(mills);
        return mills;

    }

    @Override
    public String getEngineeringAddress() {
        return edt__engineering_address.getText().toString().trim();
    }

    @Override
    public String getEngineeringName() {
        return edt__engineering_name.getText().toString().trim();
    }

    @Override
    public double getLat() {
        if (lat > 0 && lat <= 90 || lat < 0 && lat >= -90)
            return lat;
        else
            return 43.88; //默认 吉林省
    }

    @Override
    public double getLon() {
        if (lon > 0 && lon <= 180 || lon < 0 && lon >= -180)
            return lon;
        else
            return 125.25; //默认 吉林省
    }

    @Override
    public String getPicUrl() {
        return serverUrl;
    }


    @Override
    public List<ProductBean> getProductBeans() {
        return productBeanList;
    }

    @Override
    public String getProjectName() {
        return edt__project_name.getText().toString().trim();
    }

    @Override
    public void addEngineeringInstallatonOrderSuccess(String projectId) {
        Toast.makeText(this, "保存成功" + projectId, Toast.LENGTH_SHORT).show();
        Intent mIntent = new Intent();
        mIntent.putExtra(ConstantUtil.KEY_1, true);
        setResult(ConstantUtil.CREATED_ORDER, mIntent);
        finish();
    }

    @Override
    public void showFailedError(String desc) {
        Toast.makeText(this, "保存失败" + desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public String getFilePath() {
        return filePath;
    }

    @Override
    public void upLoadPhotoSuccessed(String uri) {

        serverUrl = uri;
    }

    @Override
    public void upLoadPhotoFailed(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "请输入正确工程地址！", Toast.LENGTH_SHORT).show();
            return;
        }
        lat = geoCodeResult.getLocation().latitude;
        lon = geoCodeResult.getLocation().longitude;

        addEngineeringInstallationOrderPresenter.addEngineeringInatallationOrder();

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }
}
